package controllers

import (
	//"2302a_news/cache"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"website/cache"
	"website/models"
	"website/pkg"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名 或者 密码为空",
		}

		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: pkg.Md5Str(password),
	}

	models.DB.Table("users").Where("username = ?", username).First(&user)
	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户已经存在",
		}
		c.ServeJSON()
		return
	}

	models.DB.Table("users").Create(&user)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "用户添加ok",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名 或者 密码为空",
		}

		c.ServeJSON()
		return
	}

	// 判断密码错误次数是否超过3次。如果超过3次，封禁用户 1小时
	key := "login_pwd_error_" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码错误次数超过3次，封禁用户1小时",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: password,
	}

	models.DB.Table("users").Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour)
		}
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码有误",
		}
		c.ServeJSON()
		return
	}

	cache.Rdb.Del(cache.Ctx, key) // 清空密码错误次数
	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登录ok",
	}
	c.ServeJSON()
	return
}
